package com.kermel.andromeda.action;

import android.content.Context;
import android.content.Intent;

import com.kermel.andromeda.activities.triggered.TriggeredAlarmActivity;
import com.kermel.andromeda.common.action.AbstractFutureAction;
import com.kermel.andromeda.data.Alarm;
import com.kermel.common.util.DateTimeUtils;

public class AlarmAction extends AbstractFutureAction {
    private Alarm alarm;
    private Context context;
    
    public AlarmAction(Alarm alarm, Context context) {
        this.alarm = alarm;
        this.context = context;
    }
    
    public void run() {
        
        System.out.println(String.format(">>>>>          AlarmAction triggered at: %s", DateTimeUtils.rightNowToDateStringFull()));
        System.out.println(String.format(">>>>> Alarm scheduled for triggering at: %s", DateTimeUtils.timeInMillisecondsToDateStringFull(alarm.triggerTime)));
        
        if (isAlarmReadyToBeTriggered()) {
            if (switchToTriggeredAlarmActivity()) {
                setExpired(true);
            }
        }
    }
    
    protected boolean isAlarmReadyToBeTriggered() {
        return alarm != null && alarm.enabled;
    }
    
    protected boolean switchToTriggeredAlarmActivity() {
        boolean didSwitch = false;
        
        if (context != null) {
            Intent intent = new Intent(context, TriggeredAlarmActivity.class);
            intent.putExtra(Alarm.ALARM_PARCEL_NAME, alarm);
            context.startActivity(intent);
            didSwitch = true;
        }
        
        return didSwitch;
    }
    
    public long getAlarmTriggerTime() {
        long triggerTime = Alarm.UNKNOWN_TRIGGER_TIME;
        
        if (alarm != null) {
            triggerTime = alarm.triggerTime;
        }
        
        return triggerTime;
    }
    
    public static boolean isTriggerTimeValid(long triggerTime) {
        return triggerTime != Alarm.UNKNOWN_TRIGGER_TIME;
    }
    
    public Alarm getAlarm() {
        return alarm;
    }
    
}
